package com.spzx.common.core.utils.tree;

import com.spzx.common.core.vo.BaseTreeVo;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 树形结构工具类
 */
public class TreeUtils {

    /**
     * 获取集合的树形结构
     *
     * @param allList
     * @param <T>
     * @return
     */
    public static <T extends BaseTreeVo> List<T> listTreeNodes(List<T> allList) {
        List<T> parentList = allList.stream().filter(item -> item.getParentId() == 0l)
                .collect(Collectors.toList());
        for (T parent : parentList) {
            parent.setChildren(findChildList(parent, allList));
        }
        return parentList;
    }

    /**
     * 获取父节点对应的子集合
     *
     * @param parent
     * @param allList
     * @param <T>
     * @return
     */
    private static <T extends BaseTreeVo> List findChildList(T parent, List<T> allList) {
        List<T> childList = new ArrayList<>();
        allList.forEach(item -> {
            if (item.getParentId().equals(parent.getId())) {
                childList.add(item);
            }
        });
        if (!CollectionUtils.isEmpty(childList)) {
            for (T t : childList) {
                findChildList(t, allList);
            }
        }
        parent.setChildren(childList);
        return childList;
    }
}
